import basic
import bs4
import re
from bs4 import BeautifulSoup as bs


class CourseSelect(basic.JwcMain):
    '''
    For 全校性选修课
    '''

    class Course():

        def __init__(self, courseName, courseCode, teacher, time, place, credit, classesPerWeek, start_end,
                     courseBelong, zone, school=None):
            self.courseName = courseName
            self.courseCode = self.codeTranslate(courseCode)
            self.teacher = teacher
            self.time = time
            self.place = place
            self.credit = credit
            self.classesPerWeek = classesPerWeek
            self.start_end = start_end
            self.courseBelong = courseBelong
            self.zone = zone
            self.school = school

        @staticmethod
        def codeTranslate(code):
            import re
            match = re.search(r'\(\d+-\d+-\d*\)-(\d+)-\d+-\d*', code)
            if match:
                return match.group(1)
            else:
                return code

    def __init__(self):
        super(CourseSelect, self).__init__()
        if '全校性选修课' not in self.functionEntrace:
            raise self.NotAble
        self.functionPageUrl = self.functionEntrace['全校性选修课']
        response = self.get(self.functionPageUrl)
        self.soup = bs(response.text, 'html5lib')
        self.viewstate = self.soup.find(attrs={'name': '__VIEWSTATE'})['value']
        self.getMyCourse(self.soup)

    def getPage(self, classBelong, classRemain, classZone):
        param = [('__EVENTTARGET', 'ddl_kcgs'),
                 ('__EVENTARGUMENT', ''),
                 ('__VIEWSTATE', self.viewstate),
                 ('ddl_kcxz', ''),
                 ('ddl_ywyl', classRemain),
                 ('ddl_kcgs', classBelong),
                 ('ddl_sksj', ''),
                 ('ddl_xqbs', classZone),
                 ('TextBox1', '')]
        response = self.post(url=self.functionPageUrl, data=param, encodeParam=True)
        self.soup = bs(response.text, 'html5lib')

    def getMyCourse(self, soup):
        trlist = soup.find(id='DataGrid2').find('tbody')
        courselist = []
        for tr in trlist:
            if not isinstance(tr, bs4.element.Tag) or (tr.get('class') and 'datagridhead' in tr.get('class')): continue
            tdlist = tr.find_all('td')
            courselist.append(self.Course(courseName=tdlist[1].text, courseCode=tdlist[0].text, teacher=tdlist[2].text,
                                          credit=tdlist[3].text, classesPerWeek=tdlist[4].text,
                                          start_end=tdlist[5].text,
                                          zone=tdlist[6].text, time=tdlist[7].text, place=tdlist[8].text,
                                          courseBelong=tdlist[10].text))
        return courselist

    def quitCourse(self, pattern, soup):
        trlist = soup.find(id='DataGrid2')
        td = trlist.find("td", text=re.compile(pattern))
        if not td:
            self.log("quitClass " + pattern + ": not exits")
            return
        jstext = td.parent.find('a')['href']
        courseCode = td.parent.find('td').text
        target = re.search(r"doPostBack\('([^']+)", jstext).group(1).replace('$', ':')
        viewstate = soup.find(attrs={'name': '__VIEWSTATE'})['value']
        param = [('__EVENTTARGET', target),
                 ('__EVENTARGUMENT', ''),
                 ('__VIEWSTATE', viewstate)]
        optlist = soup('option', selected="selected")
        for opt in optlist:
            name = opt.parent['name']
            value = opt['value']
            param.append((name, value))
        param.append(("TextBox1", ""))
        response = self.post(self.functionPageUrl, param, True)
        soup = bs(response.text, 'html5lib')
        trlist = soup.find(id='DataGrid2')
        if trlist.find(text=courseCode):
            self.log("quitClass " + pattern + ": failed")
            return
        else:
            return soup

    def selectCourse(self, soup, code):
        table = soup.find("table")
        td = table.find('td', text=code)
        selectCode = td.parent.find("input")['name']
        viewstate = soup.find(attrs={'name': '__VIEWSTATE'})['value']
        param = [('__EVENTTARGET', ''),
                 ('__EVENTARGUMENT', ''),
                 ('__VIEWSTATE', viewstate)]
        optlist = soup('option', selected="selected")
        for opt in optlist:
            name = opt.parent['name']
            value = opt['value']
            param.append((name, value))
        param.append(("TextBox1", ""))
        param.append((selectCode, "on"))
        param.append(("Button1", "  提交  "))
        response = self.post(self.functionPageUrl, param, True)
        soup = bs(response.text, 'html5lib')
        alert = soup.find("script", text=re.compile("alert"))
        if alert:  # something wrong
            errText = re.search(r"alert\('(.+?)'\)", alert.text).group(1)
            if re.search("现在不是选课时间", errText):
                self.log("selectCourse" + code + "failed:" + errText)


if __name__ == "__main__":
    a = CourseSelect()
    a.selectCourse(a.soup, "99900618")
